package com.surpassun.emall.repository;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.stereotype.Repository;

import com.surpassun.emall.model.Product;
import com.surpassun.emall.util.Validator;

/**
 *
 * @author Denis
 */
@Repository
public class ProductRepository extends AbstractRepository<Product> {
	
    public ProductRepository() {
        super(Product.class);
    }

	@SuppressWarnings("unchecked")
	public List<Product> searchProducts(String keyword, long cityId) {
		Session session = null;
		List<Product> result = null;
		try {
			session = getHibernateSession();
			if (Validator.isNotNull(session)) {
				Criteria criteria = session.createCriteria(Product.class);
				Criterion keyWordCriterion = Restrictions.and(Restrictions.like("name", keyword),
						Restrictions.like("description", keyword),
						Restrictions.like("category.name", keyword),
						Restrictions.like("store.name", keyword));
				if (cityId > 0) {
					Criterion cityCriterion = Restrictions.eq("store.address.city.id", cityId);
					criteria.add(Restrictions.and(keyWordCriterion, cityCriterion));
				} else {
					criteria.add(keyWordCriterion);
				}
				
				result = (List<Product>)criteria.list();
			}
		} finally {
			if (Validator.isNotNull(session) && session.isOpen()) {
				session.close();
			}
		}
		
		return result;
	}
}